package pw.hais.znyj.base.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.squareup.okhttp.Response;

import java.util.HashMap;
import java.util.Map;

import pw.hais.http.Http;
import pw.hais.http.base.OnHttpListener;
import pw.hais.utils.L;
import pw.hais.znyj.R;
import pw.hais.znyj.base.app.BaseActivity;
import pw.hais.znyj.base.app.HaisApp;
import pw.hais.znyj.base.app.V;
import pw.hais.znyj.mod.led.LedActivity;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private EditText edit_ip;
    private Button btn_reboot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        findViewById(R.id.btn_led).setOnClickListener(this);
        btn_reboot = (Button) findViewById(R.id.btn_reboot);
        btn_reboot.setOnClickListener(this);

        edit_ip = (EditText) findViewById(R.id.edit_ip);
        edit_ip.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                V.LOCALHOST = "http://"+edit_ip.getText().toString();
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                V.LOCALHOST = "http://"+edit_ip.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            L.showShort("再次按返回键退出 " + getResources().getString(R.string.app_name));
            exitTime = System.currentTimeMillis();
        } else {
            ((HaisApp) getApplication()).exitApp();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_led:
                startActivity(new Intent(context, LedActivity.class));
                break;
            case R.id.btn_reboot:
                Map<String, String> data = new HashMap<>();
                data.put("shell", "sudo reboot ");
                Http.post(V.LOCALHOST+"/doShell.php", data, new OnHttpListener<String>() {
                    @Override
                    public void onSuccess(Response response, String data) {
                        L.e("-------" + data);
                    }
                });
                break;
        }
    }
}
